package com.ds.yuntukubackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ds.yuntukubackend.config.CosClientConfig;
import com.ds.yuntukubackend.exception.BusinessException;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.manager.CosManager;
import com.ds.yuntukubackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     * @param inputSource 文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix){
        //1.校验图片
        validPicture(inputSource);
        //2.图片上传地址
        //图片名称: 时间戳 + 随机数 + 文件后缀
        String uuid = RandomUtil.randomString(8);
        //获取原始文件名
        String originalFilename =  getOriginFilename(inputSource);
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,fileSuffix);
        //图片上传地址, uploadPathPrefix可以指定为不同的用户id,实现不同用户的图片上传到不同的文件夹
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        //上传图片
        File file = null;
        try {
            //3.创建临时文件
            file = File.createTempFile(uploadPath, null);
            //处理文件来源（将文件下载到缓冲区）
            processFile(inputSource,file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //获取到图片处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                ///获得压缩后的文件信息
                CIObject compressedCiObject = objectList.get(0);
                //获取缩略图,默认等于压缩图
                CIObject thumbnailCiObject = compressedCiObject;
                if(objectList.size()>1){
                    thumbnailCiObject = objectList.get(1);
                }
                //封装压缩图的返回结果
                return buildResult(originalFilename,compressedCiObject,thumbnailCiObject);
            }

            return buildResult( originalFilename,file,uploadPath,imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败 :",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
        }finally {
            //清理临时文件
            this.deleteTempFile(file);
        }
    }

    /**
     * 封装返回结果
     * @param originalFilename  原始文件名
     * @param compressedCiObject    压缩后的文件
     * @param thumbnailCiObject 缩略图
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        int width = compressedCiObject.getWidth();
        int height = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(width * 1.0 / height ,2).doubleValue();
        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //设置压缩后的原图地址
        //uploadPath为相对路径，加上host域名为绝对路径
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        //设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }

    /**
     * 校验输入源的图片(本地文件或url)
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource) ;

    /**
     * 获取输入源的原始文件名称
     * @param inputSource
     * @return
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 封装返回结果
     * @param imageInfo
     * @param uploadPath
     * @param originalFilename
     * @param file
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, File file, String uploadPath ,ImageInfo imageInfo) {
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        double picScale = NumberUtil.round(width * 1.0 / height ,2).doubleValue();
        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //uploadPath为相对路径，加上host域名为绝对路径
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        return uploadPictureResult;
    }

    /**
     * 删除临时文件
     * @param file
     */
    private void deleteTempFile(File file) {
        if(file == null){
            return;
        }
        //删除临时文件
        boolean deleteResult = file.delete();
        if(!deleteResult){
            log.error("临时文件删除失败，文件地址：{}",file.getAbsolutePath());
        }
    }


}
